$(document).ready(function() {

	Invitesq.PhotoModel = Backbone.Model.extend({
		defaults : {
			"src" : "",
			"progress" : 0,
			"caption" : "No caption",
			"id": ""
		}
	}); 
	
	Invitesq.AlbumModel = Backbone.Model.extend({
		defaults : {
			"id" : -1,
			"title" : "Untitled Album",
			"description" : "No Description",
		}
	});


	// This hold all photo being added to browser
	Invitesq.ThumbnailCollection = Backbone.Collection.extend({
		model: Invitesq.PhotoModel
	});
	
	Invitesq.uploadAlbumTemplate = function() {
		return '' +
		'<div class="row-fluid" id="upload-album-header">' + 
			'<div class="span7">' +
				'<input type="text" id="album-title" class="editable-input span12" placeholder="Untitled Album"  value = "Untitled Album" style="font-size:17px; font-weight: bold;"/>'  +
				'<input type="text" id="album-desc" class="editable-input span12" placeholder="Give some description for this album"   />' +
			'</div>' +
			'<div class="span5" id="drop-menu-right">' +
				'<input type="text" class="span12" placeholder="Add a location" id="album-title" />'  +
				'<button class="btn" id="browse-album">Browse</button>' +
				'<button class="btn btn-primary" id="upload">Save Album</button>' +
			'</div>' +
		'</div>' +
		'<div class="row-fluid" id="upload-album-main">' +
			//'<div class="span5">' +
			//	'<div id="drop-area" style="height:200px;border:1px;border-style:solid;"></div>' +
			//'</div>' +
		'</div>' +
		
		'<div class="row-fluid" id="upload-album-footer">' +
			'<div class="span5">' +
				'<p> Footer</p>' +
			'</div>' +
		'</div>' 
		;
	};
	
	Invitesq.thumbnailCollectionTemplate = function() {
		return '' 
		//'<h1>Drag and Drop here</h1>'+
		//'<img id="dragdropImg" style="margin-left:30%; margin-top:0%;" src="/assets/img/DropBox.png">'
		;
	}
	
	Invitesq.thumbnailTemplate = function() {
		return '' +
			'<div class="remove-btn" title="Remove this photo" id="<%= id %>"/>' +
			'<img src="<%=  src %>"/>' +
			'<div class="progress">' +
				'<div class="bar" style="width: <%=progress%>%;"></div>' +
			'</div>' +
			'<textarea rows="2" class="editable-input photo-caption span12" placeholder="Add a caption for this photo" ></textarea>' 
			; 
	};
	
	// For individual view: thumbnail + progress slider
	// Bind to a model
	// It simply refreshes when model is changed
	Invitesq.ThumbnailView =  Backbone.View.extend({
		tagName : "div",
		className : "thumbnail",
		
		template : _.template(Invitesq.thumbnailTemplate()),
		
		events: {
			"blur .photo-caption": "updateCaption"
		},
		
		initialize : function() {
			_.bindAll(this, 'render');
			this.model.on("change", this.render, this);
		},
		
		updateCaption: function(e) {
			//console.log("Caption" + $(e.target).val());
			this.model.caption = $(e.target).val();
		},
		
		render: function() {
			$(this.el).html(this.template(this.model.toJSON()));
			return this;
		}		
	});
	
	// Hold all thumbnail view
	// Auto add view when collection add model
	Invitesq.ThumbnailCollectionView = Backbone.View.extend({
		tagName: "div",
		
		id: "drop-area",
		
		className: "span12",
		
		template: _.template(Invitesq.thumbnailCollectionTemplate()),
		
		
		initialize: function() {
			_.bindAll(this, 'render', 'addOne', 'removeOne');
			// Auto add view when collection add model
			Invitesq.thumbnailCollection.on('add', this.addOne, this);
			Invitesq.thumbnailCollection.on('remove', this.removeOne, this);
		},
		
		render: function() {
			$(this.el).html(this.template({}));
			return this;
		},
		
		addOne: function(model) {
			var thumbnailView = new Invitesq.ThumbnailView({model: model});
			$(this.el).append(thumbnailView.render().el);
		},
		
		// Remove photo
		removeOne: function(model) {
			console.log("remove photo " + model.id);
			$("#"+model.id).parent().remove();
		}
	});
	
	// Upload album view contains all elements
	Invitesq.UploadAlbumView = Backbone.View.extend({
		tagMame : "div",
		
		className : "span9",
		
		id: "upload-album-view",
		
		model: new Invitesq.AlbumModel(),
		
		albumId: -1,

		template : _.template(Invitesq.uploadAlbumTemplate()),

		dropAreaCss_in : {'background-color' : '#F7F7F7'},
		
		dropAreaCss_out : {'background-color' : '#EEEEEE'},
		
		uploaderOptions : {
			runtimes : 'html5',
			browse_button : 'browse-album',
			container : 'upload-album-view',
			max_file_size : '10mb',
			drop_element : "drop-area",

			filters : [{
				title : "Image files",
				extensions : "jpg,gif,png,jpeg"
			}]
		},


		initialize : function() {
			_.bindAll(this, 'render', 'dropHandler', 'uploadHandler', 'uploadToAlbum', 'dragEnterHandler', 'dragLeaveHandler', 'removeHandler');
			// Initialize new ThumbnailCollection
			Invitesq.thumbnailCollection = new Invitesq.ThumbnailCollection();
			// Assign Album Id 
			if (this.options.albumId) 
			{
				this.albumId = this.options.albumId;
				this.model.set({id: this.albumId}) ;
			}
		}, 
		


		initUploader: function() {
			this.uploader = new plupload.Uploader(this.uploaderOptions);
			// For AppEngine. the URL is dynamic, hence we need to
			// overwrite the settings before the file is uploaded
			this.uploader.bind('UploadFile', function(up, file) {
				console.log('[UploadFile]', file);
				$.ajax({
					url : '/api/photo/get-upload-url/',
					async : false,
					success : function(data) {
						up.settings.url = data;
						console.log(up.settings.url);

					},
				});
			});

			this.uploader.init();

			// When file is uploaded, change progress of model. This will propagate
			// to the corresponding view
			this.uploader.bind('UploadProgress', function(up, file) {
				var photo = Invitesq.thumbnailCollection.get(file.id);
				photo.set({
					progress : file.percent
				});
				console.log(photo);
			});

			var $this = this;

			// When file is added, create new model and set model id
			// Also add it to the collection

			this.uploader.bind('FilesAdded', function(up, files) {
				console.log("files " + files.length);
				$.each(files, function(i, file) {
					console.log("FileAdded" );

					// Create new photoModel and add to collection
					var photoModel = new Invitesq.PhotoModel();
					Invitesq.thumbnailCollection.add(photoModel);

					// Set attributes
					photoModel.set({
						id : file.id
					});

					// Read file and parse result to src
					var reader = new FileReader();
					reader.onload = function(e) {
						photoModel.set({
							src : e.target.result
						});
					};

					reader.readAsDataURL(file.nativeFile);
				});
	
				up.refresh();
				// Reposition Flash/Silverlight
			});
			
			this.uploader.bind('BeforeUpload', function(up, file) {
				// Asign other photo's properties before upload
				console.log("file " + file.id);
				var photo = Invitesq.thumbnailCollection.get(file.id);
				up.settings.multipart_params.photo_description = photo.caption;
			});
			
		},


		
		events : {
			"drop #drop-area" : "dropHandler",
			"click #upload" : "uploadHandler",
			"dragover #drop-area" : "dragEnterHandler",
			"dragleave #drop-area" : "dragLeaveHandler",
			"click .remove-btn" : "removeHandler",
			"blur #album-title" : "updateModel",
			"blur #album-desc" : "updateModel",
		},
		
		render: function() {
			$(this.el).html(this.template({}));
			var thumbnailCollectionView = new Invitesq.ThumbnailCollectionView();
			this.$("#upload-album-main").append(thumbnailCollectionView.render().el);
			// Add scrollbar for drop-area 
			this.$("#drop-area").slimScroll({
				  width: '100%',
				  height: this.$("#drop-area").height,
				  position: 'right',
				  start: 'bottom',
				  allowPageScroll: false
			});
			return this;
		},

		dropHandler : function(e) {
			$this = this;
			console.log("Files are dropped in drop area");
			this.$('#drop-area').css(this.dropAreaCss_out);
		},
			
		uploadHandler : function(e) {
			// Fall back:  if still no id then create an album
			var $this = this;
			var albumData = this.model.toJSON();
			albumData.event_id = Invitesq.eventId;
			
			if (this.albumId == -1) 
			{
				// Create album
				$.post("/api/album/create/", albumData, function(album){
					console.log("Created new album with id:" + album.id);
					$this.albumId = album.id;
					$this.uploadToAlbum();
				});
			}
			else {
				console.log("Updating album with id:" + this.albumId + " " + albumData );
				$.post("/api/album/update/", albumData, this.uploadToAlbum);
			}
			e.preventDefault();
		},
		
		
		uploadToAlbum : function() {
			this.uploader.settings.multipart_params = {
				"album_id": this.albumId,
				"event_id": Invitesq.eventId
			};
			this.uploader.start();
		},
		
		updateModel : function() {
			this.model.set({
				title: this.$("#album-title").val(),
				description: this.$("#album-desc").val()
			});	
		},
		
		dragEnterHandler : function() {
			console.log("File is dragged into browser");
			this.$('#drop-area').css(this.dropAreaCss_in);
			return false;
		},
		
		dragLeaveHandler : function() {
			console.log("File is dragged out of browser");
			this.$('#drop-area').css(this.dropAreaCss_out);
			return false;
		},
		
		removeHandler : function(e){
			var $this = this;
			var currentId  = e.target.id;
			var new_upload = false;
			console.log("currentid " + currentId);
			// Remove from collection ui
			var photo = Invitesq.thumbnailCollection.get(currentId);
			Invitesq.thumbnailCollection.remove(photo);
			
			// Remove from uploader file list
			var file = this.uploader.getFile(currentId);
			this.uploader.removeFile(file);
			console.log("removefile " + file.id);
	        
		},
		
	});

	Invitesq.AlbumView = Backbone.View.extend({});
	});
